<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <!-- 引入样式 -->
  <link rel="stylesheet" href="../../plugins/element-ui/index.css" />
  <link rel="stylesheet" href="../../styles/common.css" />
  <link rel="stylesheet" href="../../styles/page.css" />

  <style>
    #combo-add-app .uploadImg .el-form-item__label::before{
      content: '*';
      color: #F56C6C;
      margin-right: 3px;
    }
    .avatar-uploader .el-upload {
      width: 160px;
      height: 160px;
    }
    .avatar-uploader .el-upload img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  </style>
</head>
<body>
   <div class="dashboard-container" id="food-app">
    <div class="container">
      <div class="tableBar">
        <el-input
          v-model="input"
          placeholder="请输入汽车名称"
          style="width: 250px"
          clearable
          @keyup.enter.native="handleQuery"
        >
          <i
            slot="prefix"
            class="el-input__icon el-icon-search"
            style="cursor: pointer"
            @click="init"
          ></i>
        </el-input>
        <div class="tableLab">
          <span class="span-btn delBut non" @click="deleteHandle('批量', null)">删除车辆</span>
          <span class="span-btn blueBug non" @click="statusHandle('1')">批量启租</span>
          <span style="border:none;" class="span-btn delBut non" @click="statusHandle('0')">批量停租</span>
          <el-button
            type="primary"
            @click="addClass()"
          >
            + 新增车辆
          </el-button>
        </div>
      </div>
      <el-table
        :data="tableData"
        stripe
        class="tableBox"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="25"
        ></el-table-column>
        <el-table-column
          prop="carName"
          label="汽车名称"
        ></el-table-column>
        <el-table-column prop="url" label="汽车图片"  align="center">
          <template slot-scope="{ row }">
            <el-image style="width: auto; height: 40px; border:none;cursor: pointer;" :src="getImage(row.url)" :preview-src-list="[ `/common/download?name=${row.url}` ]" >
              <div slot="error" class="image-slot">
                <img src="./../../images/noImg.png"  style="width: auto; height: 40px; border:none;" >
              </div>
            </el-image>
          </template>
        </el-table-column>
          <el-table-column
                  prop="lp"
                  label="牌照"
          ></el-table-column>

        <el-table-column
          prop="carType"
          label="汽车类别"
        ></el-table-column>
        <el-table-column
                prop="carPrice"
                label="租赁价格"
        >

        </el-table-column>
        <el-table-column
                prop="rentalStatus"
                label="租赁状态">
          <template slot-scope="scope">
            <span style="margin-right: 10px;">{{ scope.row.rentalStatus == '0' ? '停租' : '启租' }}</span>
          </template>
        </el-table-column>

        </el-table-column>
        <el-table-column
          label="操作"
          width="160"
          align="center"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              class="blueBug"
              @click="editHandle(scope.row)"
            >
              修改
            </el-button>
            <el-button
              type="text"
              size="small"
              class="blueBug"
              @click="statusHandle(scope.row)"
            >
              {{ scope.row.rentalStatus == '0' ? '启租' : '停租' }}
            </el-button>
            <el-button
              type="text"
              size="small"
              class="delBut non"
              @click="deleteHandle('单删', scope.row.carId)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pageList"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="counts"
        @size-change="handleSizeChange"
        :current-page.sync="page"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
     <el-dialog
             :title="classData.title"
             :visible.sync="classData.dialogVisible"
             width="30%"
             :before-close="handleClose"
     >
       <el-form
               class="demo-form-inline"
               label-width="100px"
       >
         <el-form-item label="车辆名称：">
           <el-input
                   v-model="classData.carName"
                   placeholder="请输入车辆名称"
                   maxlength="14"
           />

         </el-form-item>
         <el-form-item label="车牌号：">
           <el-input v-model="classData.lp"   placeholder="请输入汽车车牌号" />
         </el-form-item>
         <el-form-item label="汽车类别：">
           <el-select v-model="classData.carType" placeholder="请选择汽车类别">
             <el-option label="轿车" value="轿车"></el-option>
             <el-option label="SUV" value="SUV"></el-option>
             <el-option label="MPV" value="MPV"></el-option>
             <el-option label="跑车" value="跑车"></el-option>
             <el-option label="皮卡" value="皮卡"></el-option>
             <el-option label="面包车" value="面包车"></el-option>
           </el-select>
         </el-form-item>
         <el-form-item label="租赁价格：">
           <el-input v-model="classData.carPrice"   placeholder="请输入租赁价格" />
         </el-form-item>
         <el-form-item label="租赁状态：">
           <el-select v-model="classData.rentalStatus" placeholder="请选择租赁状态">
             <el-option label="停租" value="0"></el-option>
             <el-option label="启租" value="1"></el-option>
           </el-select>
         </el-form-item>
         <el-form-item label="管理员编号：">
           <el-input v-model="classData.adminId"   placeholder="请输入管理员编号" />
         </el-form-item>
         <el-form-item label="汽车颜色：">
           <el-select v-model="classData.carColor" placeholder="请选择汽车颜色">
             <el-option label="黑色" value="黑色"></el-option>
             <el-option label="白色" value="白色"></el-option>
             <el-option label="红色" value="红色"></el-option>
             <el-option label="蓝色" value="蓝色"></el-option>
             <el-option label="银色" value="银色"></el-option>
             <el-option label="灰色" value="灰色"></el-option>
           </el-select>
         </el-form-item>
         <el-form-item label="汽车图片：" class="uploadImg">
             <el-upload
                     class="avatar-uploader"
                     action="/common/upload"
                     :show-file-list="false"
                     ref="upload"
                     :on-success="handleAvatarSuccess"
                     :on-change="onChange"
               >
               <img v-if="imageUrl" :src="imageUrl" class="avatar"></img>
               <i v-else class="el-icon-plus avatar-uploader-icon"></i>
             </el-upload>
<!--               <el-input v-model="classData.url"   placeholder="请输入汽车图片地址" />-->
         </el-form-item>
       </el-form>
       <span
               slot="footer"
               class="dialog-footer"
       >
        <el-button
                size="medium"
                @click="classData.dialogVisible = false"
        >取 消</el-button>
        <el-button
                type="primary"
                size="medium"
                @click="submitForm()"
        >确 定</el-button>

      </span>
     </el-dialog>
  </div>
    <!-- 开发环境版本，包含了有帮助的命令行警告 -->
    <script src="../../plugins/vue/vue.js"></script>
    <!-- 引入组件库 -->
    <script src="../../plugins/element-ui/index.js"></script>
    <!-- 引入axios -->
    <script src="../../plugins/axios/axios.min.js"></script>
    <script src="../../js/request.js"></script>
    <script src="../../api/food.js"></script>
    <script>
      new Vue({
        el: '#food-app',
        data() {
          return {
            imageUrl : '',
             input: '',
             counts: 0,
             page: 1,
             pageSize: 10,
             tableData : [],
             dishState : '',
             checkList: [],
            classData: {

              'title': '',
              'dialogVisible': false,
              'carName': '',
              'carType':'',
              'lp': '',
              'carPrice': '',
              'rentalStatus':'',
              'carId': '',
              'adminId':'',
              'carColor':'',
              'url':'',

            }
          }
        },
        computed: {},
        created() {
          this.init()
        },
        mounted() {
        },
        methods: {
          async init () {
            const params = {
              page: this.page,
              pageSize: this.pageSize,
              name: this.input ? this.input : undefined
            }
            await getDishPage(params).then(res => {
              if (String(res.code) === '1') {
                this.tableData = res.data || []
                this.counts = res.total
              }
            }).catch(err => {
              this.$message.error('请求出错了：' + err)
            })
          },
          handleAvatarSuccess (response, file, fileList) {
            // this.imageUrl = response.data
            if(response.code === 0 && response.msg === '未登录'){
              window.top.location.href = '/backend/page/login/login.html'
            }else{
              this.imageUrl = `/common/download?name=${response.data}`
              this.classData.url = response.data
            }
          },
          onChange (file) {
            if(file){
              const suffix = file.name.split('.')[1]
              const size = file.size / 1024 / 1024 < 2
              if(['png','jpeg','jpg'].indexOf(suffix) < 0){
                this.$message.error('上传图片只支持 png、jpeg、jpg 格式！')
                this.$refs.upload.clearFiles()
                return false
              }
              if(!size){
                this.$message.error('上传文件大小不能超过 2MB!')
                return false
              }
              return file
            }
          },

          handleQuery() {
            this.page = 1;
            this.init();
          },
          addClass(st) {
              this.classData.title = '新增车辆'
            this.action = 'add'
            this.classData.carName = ''
            this.classData.lp = ''
            this.classData.carType = ''
            this.classData.carPrice = ''
            this.classData.rentalStatus= ''
            this.classData.carId =''
              this.classData.adminId =''
              this.classData.carColor =''
              this.classData.url =''
            this.imageUrl = ''
            this.classData.dialogVisible = true
          },
          editHandle(dat){
            this.classData.title = '修改车辆信息'
            this.action = 'edit'
            this.classData.carName = dat.carName
            this.classData.lp = dat.lp
            this.classData.carType = dat.carType
            this.classData.carPrice = dat.carPrice
            this.classData.rentalStatus = dat.rentalStatus
            this.classData.carId = dat.carId;
              this.classData.adminId = dat.adminId;
              this.classData.carColor = dat.carColor;
              this.classData.url = dat.url;
              this.imageUrl = this.getImage(dat.url)
            this.classData.dialogVisible = true
          },
          //数据提交
          submitForm(st) {
            const classData = this.classData
            const nameMap = {
              carName: '车辆名称',
              lp: '车牌号',
              carType: '汽车类别',
              carPrice: '租赁价格',
              rentalStatus: '租赁状态',
              adminId: '管理员编号',
              carColor: '汽车颜色',
              url: '汽车图片'
            }

            // 检查classData的每个参数是否为空
            for (let key in classData) {
              if (classData[key] === null || classData[key] === '') {
                // 使用映射对象获取对应的文字
                if (key === 'carId')continue
                console.log(key)
                this.$message.error(nameMap[key] + ' 不能为空！');
                return;
              }
            }

            const  valid = 1
            if (this.action === 'add') {

                const reg = /^\d+$/
                // reg.test(classData.sort)
                  addDish(this.classData).then(res => {
                    console.log(res)
                    if (res.code === 1) {
                      this.$message.success('汽车添加成功！')
                      if (!st) {
                        this.classData.dialogVisible = false
                      } else {
                        this.classData =''
                        this.imageUrl = ''
                        // this.classData.sort = ''
                      }
                      this.handleQuery()
                    } else {
                      this.$message.error(res.msg || '操作失败')
                    }
                  }).catch(err => {
                    this.$message.error('请求出错了：' + err)
                  })


            } else if (valid) {
              const reg = /^\d+$/
              // reg.test(this.classData.sort)
              if (1) {
                const params = {
                  carName: this.carName,
                  lp: this.lp,
                  carType: this.carType,
                  carPrice: this.carPrice,
                  rentalStatus: this.rentalStatus
                }
                editFood(classData).then(res => {
                  if (res.code === 1) {
                    this.$message.success('汽车数据修改成功！')
                    this.classData.dialogVisible = false
                    this.handleQuery()
                  } else {
                    this.$message.error(res.msg || '操作失败')
                  }
                }).catch(err => {
                  this.$message.error('请求出错了：' + err)
                })
              } else {
                this.$message.error('排序只能输入数字类型')
              }
            } else {
              this.$message.error('请输入分类名称或排序')
            }
          },
          getImage (image) {
            return `/common/download?name=${image}`
          },

          // 删除
          deleteHandle (type, id) {
            if (type === '批量' && id === null) {
              if (this.checkList.length === 0) {
                return this.$message.error('请选择删除对象')
              }
            }
            this.$confirm('确认删除该车辆, 是否继续?', '确定删除', {
              'confirmButtonText': '确定',
              'cancelButtonText': '取消',
            }).then(() => {
              deleteDish(type === '批量' ? this.checkList.join(',') : id).then(res => {
                if (res.code === 1) {
                  this.$message.success('删除成功！')
                  this.handleQuery()
                } else {
                  this.$message.error(res.msg || '操作失败')
                }
              }).catch(err => {
                this.$message.error('请求出错了：' + err)
              })
            })
          },
          handleClose() {
            this.imageUrl = '';
            this.classData.url = '';
          },
          //状态更改
          statusHandle (row) {
            let params = {}
            if (typeof row === 'string' ) {
              if (this.checkList.length === 0) {
                this.$message.error('批量操作，请先勾选操作车辆！')
                return false
              }
              params.id = this.checkList.join(',')
              params.status = row
            } else {
              params.id = row.carId
              params.status = row.rentalStatus ? '0' : '1'
            }
            this.dishState = params
            this.$confirm('确认更改车辆状态?', '提示', {
              'confirmButtonText': '确定',
              'cancelButtonText': '取消',
              'type': 'warning'
            }).then(() => {
              // 起售停售---批量起售停售接口
              dishStatusByStatus(this.dishState).then(res => {
                if (res.code === 1) {
                  this.$message.success('汽车状态已经更改成功！')
                  this.handleQuery()
                } else {
                  this.$message.error(res.msg || '操作失败')
                }
              }).catch(err => {
                  this.$message.error('请求出错了：' + err)
              })
            })
          },

          // 全部操作
          handleSelectionChange (val){
            let checkArr = []
            val.forEach((n) => {
              checkArr.push(n.carId)
            })
            this.checkList = checkArr
          },
          handleSizeChange (val) {
            this.pageSize = val
            this.init()
          },
          handleCurrentChange (val) {
            this.page = val
            this.init()
          },
        }
      })
    </script>
</body>
</html>